package com.szrt.socket.ch02.tcp.demo03;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.junit.Test;

/**
 * 使用tcp协议让客户端给服务端发送文本。服务端把文本转成大写再返回给客户端。
 *
 */
public class TCPTest {
	
	/**
	 * 客户端
	 */
	@Test
	public void client() throws Exception{
		//1
		Socket socket  = new Socket(InetAddress.getByName("127.0.0.1"),9090);
		
		//2
		OutputStream os = socket.getOutputStream();
		
		//3
		os.write("abcdef".getBytes()); //7
		
		
		//4接收来自服务端的数据
		socket.shutdownOutput(); 
		
		InputStream is = socket.getInputStream();
		byte[] b = new byte[4];
		int len;
		String str = "";
		while((len = is.read(b)) != -1){
			//7=4+3
			String str1 =new String(b,0,len);
			str = str + str1;
		}
		System.out.println("客户端接收到服务端返回过来的数据："+str);
		
		is.close();
		os.close();
		socket.close();
	}
	
	/**
	 * 服务端
	 */
	@Test
	public void server() throws Exception{
		
		//1 
		ServerSocket ss = new ServerSocket(9090);
		
		//2
		Socket socket = ss.accept();
		
		//3 接收来自客户端的信息
		InputStream is = socket.getInputStream();
		
		byte[] b = new byte[4];
		int len;
		String str = "";
		while((len = is.read(b)) != -1){
			//7=4+3
			String str1 =new String(b,0,len);
			str = str + str1;
		}
		
		System.out.println("服务端接收到客户端发送过来的数据："+str);
		//把字符串转成大写
		String strUp = str.toUpperCase();
		
		//4把字符串返回给客户端
		OutputStream os = socket.getOutputStream();
		os.write(strUp.getBytes());
		
		//5关闭资源
		os.close();
		is.close();
		socket.close();
		ss.close();
		
		
		
	}

}
